﻿package src.common 
{
	/**
	* 
	* Reliability project
	* -----------------------
	* @author  Dmitrij Boycov
	* @mail    dmitry.boycov@gmail.com
	* @date    April 27, 2010
	* @version 1
	* 
	*/
	
	import flash.events.Event;
	import flash.events.EventDispatcher;	
	import flash.events.KeyboardEvent;
	
	import src.entity.IEntity;
	
	public class OwnerEvent extends EventDispatcher{
		
		public static const NEED_RESET_OWNER_EVENT:String =  "NEED_RESET_OWNER_EVENT";
		public static const NEED_DELETE_ENTITY:String =  "NEED_DELETE_ENTITY";
		private static var instance:OwnerEvent;
		private static var allowInstantiation:Boolean;
		private var owner:Object;
		private var activeEntity = null;
		
		/**
		 * construct
		 */
		public function OwnerEvent():void{
			if (!allowInstantiation) {
				throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
			}
		}
    
		public static function getInstance():OwnerEvent{
			if (instance == null) {
				allowInstantiation = true;
				instance = new OwnerEvent();
				allowInstantiation = false;
			}
			return instance;
		}
		
		public function setOwnerEvent(obj:Object) {
			if (obj != null) {				
				this.owner = obj;
				if (this.activeEntity != obj){		
					this.resetActiveEntity();
					if ( obj is IEntity) {
						this.activeEntity = obj;
					}
				}	
			}	
		}		
		
		/**
		 * onKeyDown
		 * This function is called from the scheme object because it listens to the keyboard.
		 * This version implementation allows you to reliably receive and process keyboard events.
		 * @param	e keybord event
		 */		  
		public function onKeyDown(e) {
			if (e.keyCode == 46 && this.activeEntity != null ) { // press delete btn				
				dispatchEvent(new Event(OwnerEvent.NEED_DELETE_ENTITY));
			}			
		}
		
		public function getOwnerEvent() {
			return this.owner;
		}
		
		public function getActiveEntity() {
			return this.activeEntity;
		}
		
		public function resetActiveEntity(){		
			if (this.activeEntity != null ) {
				if (this.activeEntity is IEntity) {							
					this.activeEntity.inactive();
				}
				this.activeEntity = null;
			}
		}
		
		public function resetOwnerEvent(){
			this.owner = null;
		}
		
		public function notifyAboutResetEvent() {
			dispatchEvent(new Event(OwnerEvent.NEED_RESET_OWNER_EVENT));
		}
	}
	
}